package com.example.order.controller;

import com.example.order.config.AppFinal;
import com.example.order.model.OrderInfo;
import com.example.order.model.UserInfo;
import com.example.order.service.OrderDetailService;
import com.example.order.service.OrderService;
import com.example.order.tools.ResponseBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;

    @RequestMapping("/add")
    public ResponseBody add(String dids , HttpServletRequest request){
        int data = 0;
        //1.添加订单
        HttpSession session = request.getSession(false);
        if(session != null && session.getAttribute(AppFinal.USERINFO_SESSION_KEY) != null){
            //当前为登录状态
            int uid = ((UserInfo)session.getAttribute(AppFinal.USERINFO_SESSION_KEY)).getId();
            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setUid(uid);
            //添加订单
            int result = orderService.add(orderInfo);
            if (result > 0) {  //订单添加成功
                //2添加订单详情
                data = orderDetailService.add(orderInfo.getId() , dids.split(","));
            }
        }

        return  new ResponseBody(0 , "" , data);
    }

    /**
     * 获取当前用户的订单列表
     * @return
     */
    @RequestMapping("/list")
    public ResponseBody getList(HttpServletRequest request){
        List<OrderInfo> list = null;
        HttpSession session = request.getSession(false);
        if(session != null && session.getAttribute(AppFinal.USERINFO_SESSION_KEY) != null){
            //当前为登录状态
            int uid = ((UserInfo)session.getAttribute(AppFinal.USERINFO_SESSION_KEY)).getId();
            list = orderService.getList(uid);
        }
        return new ResponseBody(0 , "" , list);
    }

    /**
     * 管理员查看所有订单
     * @return
     */
    @RequestMapping("/alllist")
    public ResponseBody getAllList(HttpServletRequest request){
        List<OrderInfo> list = orderService.getAllList();
        return new ResponseBody(0 , "" , list);
    }

    /**
     * 修改订单状态
     * @return
     */
    @RequestMapping("/up")
    public ResponseBody up(int oid , int status){
        int data = 0;
        data = orderService.up(oid , status);
        return new ResponseBody(0 , "" , data);
    }
}
